#include "beep.h"
#include "appconfig.h"
#include "millis.h"

static uint8_t buzzLen;
static millis8_t startTime;
static buzzFinish_f onFinish;
static tonePrio_t prio;

static void stop(void);


void buzzer_init()
{
    pwm_init(10, 4000);
}

// Start buzzing for a certain length of time
// len: 0 = forever
// tone: 0 = stop, 1 = pause, 2 = repeat
// volType: 0 = other, 1 = UI, 2 = alarm, 3 = hour
// prio: 0 = min, 1 = low, 2 = normal, 3 = high, 255 = max
// onFinish: callback function
void buzzer_buzz(uint8_t len, tone_t tone, vol_t volType, tonePrio_t _prio, buzzFinish_f _onFinish)
{
    if(_prio < prio)
		return;
	else if(tone == TONE_STOP)
	{
		stop();
		return;
	}

    prio = _prio;
	onFinish = _onFinish;
	buzzLen = len;
	startTime = millis();

    // Silent pause tone   //无声暂停音
	if(tone == TONE_PAUSE)
	{
        pwm_set_duty(0);

		return;
	}

    // Workout volume
	uint16_t ocr;
	uint8_t vol;

	switch(volType)
	{
		case VOL_UI:
			vol = appConfig.volUI;
			break;
		case VOL_ALARM:
			vol = appConfig.volAlarm;
			break;
		case VOL_HOUR:
			vol = appConfig.volHour;
			break;
		default:
			vol = 2;
			break;
	}

	// Pulse width goes down as freq goes up
	// This keeps power consumption the same for all frequencies, but volume goes down as freq goes up

	vol--;
	if(vol > 2)
	{
		return;
	}
		

	unsigned short icr = tone * (8 << 1);

	ocr = icr - (icr / (32>>vol));
    pwm_set_duty(ocr);
	//    TIM_Cmd(TIM13, ENABLE);  //开始TIM3 
	// 	  BEEP=1;
    // TIM_SetCompare1(TIM13,ocr);
}

// Are we buzzing?
bool buzzer_buzzing()
{
	return buzzLen;
}

// See if its time to stop buzzing
void buzzer_update()
{
	if(buzzLen && (millis8_t)(millis() - startTime) >= buzzLen)
	{
		stop();

		if(onFinish != NULL)
			onFinish();
	}
}

static void stop()
{
	pwm_set_duty(0);
	buzzLen = 0;
	prio = PRIO_MIN;
}